package yt.demo.appcommontools.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestUtils {


    /**
     * 获取所有请求头并组装成 Map
     *
     * @param request HttpServletRequest 对象
     * @return 请求头的 Map
     */
    public static Map<String, String> getAllRequestHeaders(HttpServletRequest request) {
        Map<String, String> headersMap = new HashMap<>();

        // 获取请求头的枚举集合
        Enumeration<String> headerNames = request.getHeaderNames();
        // 遍历所有请求头
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headersMap.put(headerName, headerValue);  // 将请求头添加到 Map 中
        }
        return headersMap;
    }


    public static String getCurrentDomain() {
        HttpServletRequest request = getRequestAttributes().getRequest();
        String serverName = request.getServerName(); // 获取域名
        int serverPort = request.getServerPort(); // 获取端口号
        String scheme = request.getScheme(); // 获取协议（http/https）

        // 判断是否在局域网
        String ipAddress = request.getLocalAddr();
        if (ipAddress.equals("0:0:0:0:0:0:0:1")) {
            ipAddress = "127.0.0.1";
        }
        // 判断是否是局域网访问，包括 localhost 和 127.0.0.1
        boolean isInLocalNetwork = ipAddress.startsWith("192.168") || ipAddress.startsWith("10.")
                || ipAddress.startsWith("172.") || ipAddress.equals("127.0.0.1")
                || serverName.equalsIgnoreCase("localhost");
        if (isInLocalNetwork) {
            // 局域网内，返回域名加端口
            return scheme + "://" + ipAddress + ":" + serverPort;
        } else {
            // 外网环境，返回域名
            return scheme + "://" + serverName;
        }
    }

    public static Map<String, String> getAllResponseHeaders(HttpServletResponse response) {
        Map<String, String> headersMap = new HashMap<>();
        // 获取请求头的枚举集合
        Collection<String> headerNames = response.getHeaderNames();
        // 遍历所有请求头
        for (String headerName : headerNames) {
            // 获取该响应头对应的值
            String headerValue = response.getHeader(headerName);
            // 将响应头名称和值存入Map
            headersMap.put(headerName, headerValue);
        }
        return headersMap;
    }

    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    public static String os(String agent) {
        String lowerAgent = agent.toLowerCase();
        Map<String, String> osMap = new HashMap<>();
        osMap.put("nt 6.1", "Windows 7");
        osMap.put("nt 6.2", "Windows 8");
        osMap.put("nt 10.0", "Windows 10");
        osMap.put("nt 11.0", "Windows 11");
        osMap.put("nt 5.1", "Windows XP");
        osMap.put("linux", "Linux");
        osMap.put("mac", "Mac");
        for (Map.Entry<String, String> entry : osMap.entrySet()) {
            if (containsIgnoreCase(lowerAgent, entry.getKey())) {
                return entry.getValue();
            }
        }
        return "未知";
    }

    public static String browser(String agent) {
        String lowerAgent = agent.toLowerCase();
        Map<String, String> browserMap = new HashMap<>();
        browserMap.put("msie", "MSIE");
        browserMap.put("edg", "Edge");
        browserMap.put("chrome", "Chrome");
        browserMap.put("firefox", "Firefox");
        browserMap.put("safari", "Safari");
        browserMap.put("opera", "Opera");
        for (Map.Entry<String, String> entry : browserMap.entrySet()) {
            if (containsIgnoreCase(lowerAgent, entry.getKey())) {
                return entry.getValue();
            }
        }
        return "未知";
    }

    private static boolean containsIgnoreCase(String str, String target) {
        return str != null && str.toLowerCase().contains(target.toLowerCase());
    }

}
